from typing import List

from fastapi import APIRouter, Path, Query, Body, Depends, HTTPException
from sqlalchemy import select, update, delete
from sqlalchemy.orm import Session

from ch04.db_main import get_session
from ch04.emp_manager.models import Employee
from ch06.schemas import EmpCreate, EmpResp

ch6 = APIRouter(prefix='/ch6', tags=['员工管理的案例'])


@ch6.post(path='/emp/', description='添加员工', response_model=EmpCreate)
def create_emp(emp: EmpCreate, session: Session = Depends(get_session)):
    # 判断员工的名字是否重复
    db_emp = session.execute(select(Employee).where(Employee.name == emp.name)).first()
    if db_emp:  # 存在则意味着有一个重复名字的员工
        raise HTTPException(status_code=405, detail='员工的名字已经存在重复的，请换一个新的名字！')

    # 需要把emp（Pydantic的模型对象） 转换成 ORM的模型对象（Employee）
    db_emp = Employee(**emp.dict())
    session.add(db_emp)
    session.commit()
    # 手动把ORM模型对象，转换为 Pydantic模型对象
    # return EmpCreate.from_orm(db_emp)
    # 自动
    return db_emp


# 响应之后的员工信息：包括该员工所在的部门信息
@ch6.get(path='/emp/{id}/', description='查询单个员工', response_model=EmpResp)
def get_emp(id: int, session: Session = Depends(get_session)):
    db_emp = session.get(Employee, id)
    if db_emp:
        return db_emp
    else:
        raise HTTPException(status_code=401, detail=f'ID为{id}，没有查到员工数据')


# 根据分页查询所有的员工
@ch6.get(path='/emp/', description='查询所有员工列表', response_model=List[EmpResp])
def get_emp(offset: int = Query(default=0, description='起始下标'), page_size:int =Query(default=5, description='每页最多显示的数量'), session: Session = Depends(get_session)):
    return session.scalars(select(Employee).offset(offset).limit(page_size)).all()


@ch6.put(path='/emp/{id}/', description='添加员工', response_model=EmpResp)
def update_emp(id:int = Path(description='需要修改的员工ID'), emp: EmpCreate = Body(description='修改的员工信息'), session: Session = Depends(get_session)):
    emp.id = id
    # model_dump 把模型对象 转换成 字典 （包含所有的属性）, 不包含为空的属性exclude_unset=True
    session.execute(update(Employee), [emp.model_dump(exclude_unset=True)])
    db_emp = session.get(Employee, id)
    session.commit()
    return db_emp


@ch6.delete(path='/emp/{id}/', description='添加员工')
def delete_emp(id:int = Path(description='需要修改的员工ID'), session: Session = Depends(get_session)):
    session.execute(delete(Employee).where(Employee.id == id))
    session.commit()
    return {'detail': 'success'}